<?php

namespace app\system\controller\finance;

use app\common\controller\System;
use app\system\controller\goods\ZipArchive;
use ba\Filesystem;
use hehe\Numeral;
use hehe\Str;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Border;
use PhpOffice\PhpSpreadsheet\Style\Fill;
use think\facade\Db;

/**
 * 商品管理
 */
class Drawback extends System {
    /**
     * Goods模型对象
     * @var object
     * @phpstan-var \app\admin\model\goods\Goods
     */
    protected object $model;

    protected string|array $defaultSortField = 'id,desc';

    protected array|string $preExcludeFields = ['id', 'create_time'];

    protected string|array $quickSearchField = [];

    public function initialize(): void {
        parent::initialize();
        $this->model = new \app\system\model\finance\Drawback();
    }
    public function add(): void
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            $data = $this->excludeFields($data);
            if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                $data[$this->dataLimitField] = $this->auth->id;
            }

            $data['trade_time'] = empty($data['trade_time']) ? null : strtotime($data['trade_time']);


            $admin = db::name('admin')->where(['id' => $data['admin_id']])->find();
            if(empty($data['money']) || $data['money'] < 0) $this->error('请输入正确的金额');
            $admin['amount'] = empty($admin['amount']) ? 0 : $admin['amount'];
            if($data['sz'] == '支出') {
                $data['expenditure'] = $data['money'] * 100;
                $data['amount'] = $admin['amount'] - $data['expenditure'];
            }else{ // 收入
                $data['income'] = $data['money'] * 100;
                $data['amount'] =  $admin['amount'] + $data['income'];
            }

            unset($data['money']);

            $result = false;
            $this->model->startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate;
                        if ($this->modelSceneValidate) $validate->scene('add');
                        $validate->check($data);
                    }
                }
                db::name('admin')->where(['id' => $admin['id']])->update(['amount' => $data['amount']]);
                $result = $this->model->save($data);
                $this->model->commit();
            } catch (Throwable $e) {
                $this->model->rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Added successfully'));
            } else {
                $this->error(__('No rows were added'));
            }
        }

        $this->error(__('Parameter error'));
    }

    /**
     * 编辑
     * @throws Throwable
     */
    public function edit(): void
    {
        $id  = $this->request->param($this->model->getPk());
        $row = $this->model->find($id);
        if (!$row) {
            $this->error(__('Record not found'));
        }

        $dataLimitAdminIds = $this->getDataLimitAdminIds();
        if ($dataLimitAdminIds && !in_array($row[$this->dataLimitField], $dataLimitAdminIds)) {
            $this->error(__('You have no permission'));
        }

        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            $data   = $this->excludeFields($data);

            if(empty($data['dk_time'])) $this->error(__('请选择打款时间'));

            $update = [
                'dk_time' => strtotime($data['dk_time'])
            ];

//            print_r($data);die;


            $result = false;
            $this->model->startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate;
                        if ($this->modelSceneValidate) $validate->scene('edit');
                        $validate->check($data);
                    }
                }
                $result = $row->save($update);
                $this->model->commit();
            } catch (Throwable $e) {
                $this->model->rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Update successful'));
            } else {
                $this->error(__('No rows updated'));
            }
        }



        $this->success('', [
            'row' => $row
        ]);
    }


    public function cancel(){
        $params = $this->request->param();
        db::name('customer_order')->where(['id' => $params['id']])->update(['dk_time' => null]);
        $this->success();
    }



    public function index(): void {
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->param('select')) {
            $this->select();
        }
        list($where, $alias, $limit, $order) = $this->queryBuilder();


        $res = $this->model->where($where)->where([
            ['order_type', '=', '出口'],
            ['drawback_amount', '>', 0],
            ['filter_id', '=', $this->filter['id']]
        ]);




        $param = $this->request->param();

        if(!empty($param['year'])){
            $res->whereYear('create_time', $param['year']);
        }
        if(!empty($param['month'])){
            if(empty($param['year'])) $this->error(__('请选择年份'));
            $month = $param['month'] < 10 ? '0' . $param['month'] : $param['month'];
            $res->whereMonth('create_time', $param['year'] . '-' . $month);
        }
        if(!empty($param['type'])){
            $res->where(['type' => $param['type']]);
        }
        if(isset($param['drawback_status']) && $param['drawback_status'] !== null && $param['drawback_status'] !== ''){
            $res->where(['drawback_status' => $param['drawback_status']]);
        }


        $res = $res->order('create_time desc')->paginate($limit);

        $list = $res->items();

        foreach($list as $key => $val){
            $list[$key]['amount'] = empty($val['amount']) ? 0 : Numeral::numberFormat($val['amount'] / 100);
            $list[$key]['cost'] = empty($val['cost']) ? 0 : Numeral::numberFormat($val['cost'] / 100);
            $list[$key]['drawback_amount'] = empty($val['drawback_amount']) ? 0 : Numeral::numberFormat($val['drawback_amount'] / 100);
            $list[$key]['refunded'] = empty($val['refunded']) ? 0 : Numeral::numberFormat($val['refunded'] / 100);
            $list[$key]['dk_status'] = empty($val['dk_time']) ? 0 : 1;
            $list[$key]['dk_time'] = empty($val['dk_time']) ? null : date('Y-m-d', $val['dk_time']);

            $list[$key]['optime2'] = empty($val['optime2']) ? null : date('Y-m-d', $val['optime2']);
            $list[$key]['optime3'] = empty($val['optime3']) ? null : date('Y-m-d', $val['optime3']);
            $list[$key]['optime4'] = empty($val['optime4']) ? null : date('Y-m-d', $val['optime4']);
            $list[$key]['optime5'] = empty($val['optime5']) ? null : date('Y-m-d', $val['optime5']);
            $list[$key]['drawback_note'] = empty($val['drawback_note']) ? null : html_entity_decode($val['drawback_note']);
        }


        // 总税额
        $drawback_amount_count = $this->model->where([
            ['drawback_amount', '>', 0],
        ])->sum('drawback_amount');
        // 已退税额
        $drawback_amount_count_true = $this->model->where([
            ['refunded', '>', 0],
        ])->sum('refunded');



        $res_drawback_amount_count_false = $drawback_amount_count - $drawback_amount_count_true;

        $this->success('', [
            'list' => $res->items(),
            'total' => $res->total(),
            'remark' => get_route_remark(),
            'drawback_amount_count' => Numeral::numberFormat($drawback_amount_count / 100),
            'drawback_amount_count_true' => Numeral::numberFormat($drawback_amount_count_true / 100),
            'drawback_amount_count_false' => Numeral::numberFormat($res_drawback_amount_count_false / 100),
        ]);
    }




}